package com.nti56.springboot.controller;



import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.util.StringUtil;
import com.nti56.springboot.cache.BaseDataCache;
import com.nti56.springboot.exception.MyRuntimeException;
import com.nti56.springboot.model.DictItem;
import com.nti56.springboot.model.MachInfo;
import com.nti56.springboot.model.MachProduct;
import com.nti56.springboot.model.MachRunTime;
import com.nti56.springboot.model.MachStatus;
import com.nti56.springboot.model.echarts.EchartsModel;
import com.nti56.springboot.service.MachInfoService;
import com.nti56.springboot.service.MachProductService;
import com.nti56.springboot.service.MachRunTimeService;
import com.nti56.springboot.service.MachStatusService;
import com.nti56.springboot.utils.Constant;
import com.nti56.springboot.utils.DateUtil;
import com.nti56.springboot.utils.DictConstant;
import com.nti56.springboot.utils.ParamUtil;
import com.nti56.springboot.utils.ParamUtil.Param;

import antlr.StringUtils;



@RequestMapping("cncEcharts")
@Controller
public class CncEchartsController extends BaseController{
    
	private static final Logger logger = LoggerFactory.getLogger(CncEchartsController.class);
	
	@Autowired
	private MachRunTimeService machRunTimeService;
	@Autowired
	private MachStatusService machStatusService;
	@Autowired
    private MachInfoService machInfoService;
	@Autowired
    private MachProductService machProductService;
	@Autowired
    private BaseDataCache baseDataCache;
	
	/**
	 * 柱状图页面
	 * @param map
	 * @param model
	 * @return
	 */
	@RequestMapping("/toRealTimeOutput")
	@RequiresPermissions("User:toUserList")
    public String toRealTimeOutput(Map<String,Object> map,Model model){
		List<DictItem> dictShiftItems = baseDataCache.getDictItemsByDictCode(DictConstant.DICT_WORK_SHIFT);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		String currYMD = df.format(new Date());
		model.addAttribute("currYMD", currYMD);
		model.addAttribute("dictShiftItems", dictShiftItems);
		List<MachInfo> machInfoAll = this.machInfoService.findAll(ParamUtil.setParam("activate", Constant.ACTIVATE_YES));
		model.addAttribute("total", machInfoAll.size());
		return "cnc/realTimeOutput";
    }
	
	/**
	 * 机台 实时状态   方块 页面
	 * @param map
	 * @param model
	 * @return
	 */
	@RequestMapping("/toRealTimeRunState")
	@RequiresPermissions("CncEcharts:toRealTimeOutput")
    public String toRealTimeRunState(HttpServletRequest request,Model model){
		List<DictItem> dictShiftItems = baseDataCache.getDictItemsByDictCode(DictConstant.DICT_WORK_SHIFT);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		String currYMD = df.format(new Date());
		model.addAttribute("currYMD", currYMD);
		model.addAttribute("dictShiftItems", dictShiftItems);
		List<MachInfo> machInfoAll = this.machInfoService.findAll(ParamUtil.setParam("activate", Constant.ACTIVATE_YES));
		List<MachInfo> machInfoList = null;
		try {
			//初始化状态
			machInfoList = this.getMachCurrentStatus(machInfoAll);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("machInfoList", machInfoList);
		String ctx = request.getContextPath();
		String machInfoDiv = this.createMachInfoDiv(ctx,machInfoList);
		model.addAttribute("machInfoDiv", machInfoDiv);
		int runCnt = 0;
		int standCnt = 0;
		int alarmCnt = 0;
		int offLineCnt = 0;
		for(MachInfo mif : machInfoList) {
			if(mif.getMachStatus()!= null && Constant.CNC_MACH_STATUS_RUNNING.contains(mif.getMachStatus())) {
				runCnt++;
			}else if(mif.getMachStatus()!= null && Constant.CNC_MACH_STATUS_STANDBY.contains(mif.getMachStatus())) {
				standCnt++;
			}else if(mif.getMachStatus()!= null && Constant.CNC_MACH_STATUS_ALARM.contains(mif.getMachStatus())) {
				alarmCnt++;
			}else if(mif.getMachStatus()!= null && Constant.CNC_MACH_STATUS_OFFLINE.contains(mif.getMachStatus())) {
				offLineCnt++;
			}else {
				runCnt++;
			}
		}
		model.addAttribute("runCnt", runCnt);
		model.addAttribute("standCnt", standCnt);
		model.addAttribute("alarmCnt", alarmCnt);
		model.addAttribute("offLineCnt", offLineCnt);
		return "cnc/realTimeRunState";
    }
	
	/**
	 * 堆叠图页面
	 * @param map
	 * @param model
	 * @return
	 */
	@RequestMapping("/toRealTimeRunStateBar")
	@RequiresPermissions("CncEcharts:toRealTimeRunState")
    public String toRealTimeRunStateBar(Map<String,Object> map,Model model){
		List<DictItem> dictShiftItems = baseDataCache.getDictItemsByDictCode(DictConstant.DICT_WORK_SHIFT);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		String currYMD = df.format(new Date());
		model.addAttribute("currYMD", currYMD);
		model.addAttribute("dictShiftItems", dictShiftItems);
		List<MachInfo> machInfoAll = this.machInfoService.findAll(ParamUtil.setParam("activate", Constant.ACTIVATE_YES));
		model.addAttribute("total", machInfoAll.size());
		return "cnc/realTimeRunStateBar";
    }
	
	/**
	 * 实时 产量 柱状图
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getRealTimeData")
    @ResponseBody
    public List getRealTimeData(HttpServletRequest request,Model model) throws Exception{
		String proDate = (String) request.getParameter("proDate");
		String shift = (String) request.getParameter("shift");
		String tableName = this.createMonthViewNams(proDate);
		//机台信息
		this.startPage(request);
		List<MachInfo> machInfoList = this.machInfoService.findAll(ParamUtil.setParam("activate", Constant.ACTIVATE_YES));
		List<MachProduct> mpList = machProductService.getRealTimeProductList(machInfoList,tableName,proDate,shift);
		List<List> data = new ArrayList<List>();
		List first = new ArrayList<>();
		first.add("product");
		first.add("实时产量");
		first.add("目标产量");
		data.add(first);
		for(MachProduct mp : mpList) {
			List list = new ArrayList();
			if(StringUtil.isEmpty(mp.getItemNo())) {
				list.add(mp.getMachNum());
			}else {
				list.add(mp.getMachNum()+" "+mp.getItemNo());
			}
			list.add(mp.getProCount()==null ? 0 : mp.getProCount());
			list.add(mp.getTargetQty()==null ? 0 : mp.getTargetQty());
			data.add(list);
		}
		return data;
    }
	
	/**
	 * 运行状态 堆叠图
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/getRunTimeData")
    @ResponseBody
    public EchartsModel getRunTimeData(HttpServletRequest request,Model model) {
		EchartsModel em = new EchartsModel();
		String proDate = (String) request.getParameter("proDate");
		String shift = (String) request.getParameter("shift");
		//机台信息
		this.startPage(request);
		List<MachInfo> machInfoList = this.machInfoService.findAll(ParamUtil.setParam("activate", Constant.ACTIVATE_YES));
		List<String> legendData = this.machRunTimeService.getBarLegend();
		List<String> yAxisData = this.machRunTimeService.getYAxisData(machInfoList, proDate, shift);
		
		Param params = ParamUtil.setParam("proDate", proDate).setParam("shift", shift);
		List<MachRunTime> runTimeList = machRunTimeService.findAll(params);
		//填充数据 
		List<Double> runData = new ArrayList<Double>();
		List<Double> standData = new ArrayList<Double>();
		List<Double> alarmData = new ArrayList<Double>();
		List<Double> offLineData = new ArrayList<Double>();
		for(MachInfo mi : machInfoList) {
			for(MachRunTime mrt : runTimeList) {
				if(mrt.getMachNum().equals(mi.getMachNum())) {
					double total = mrt.getRunTime() + mrt.getStandBy()+mrt.getAlarm()+mrt.getOffLine();
					runData.add(mrt.getRunTime());
					standData.add(mrt.getStandBy());
					alarmData.add(mrt.getAlarm());
					offLineData.add(mrt.getOffLine());
					break;
				}
			}
		}
		em.setLegendData(legendData);
		em.setYAxisData(yAxisData);
		em.setRunData(runData);
		em.setStandData(standData);
		em.setAlarmData(alarmData);
		em.setOffLineData(offLineData);
		return em;
	}
	
	private String createMonthViewNams(String proDate) throws Exception {
		Date date = DateUtil.parseDate(proDate, DateUtil.DATE_PATTERN);
		String yyyyMM = DateUtil.format(date, DateUtil.MONTH_PATTERN);
		return "`"+yyyyMM+"_view`";
		
	}
	
	/**
	 * 从 `2020-01_view` 表获取机台实时状态信息
	 * @param machInfoAll
	 * @return
	 * @throws Exception 
	 */
	private List<MachInfo> getMachCurrentStatus(List<MachInfo> machInfoAll) throws Exception{
		if(CollectionUtils.isEmpty(machInfoAll)) {
			throw new MyRuntimeException("机台基础数据不能为空");
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		String proDate = df.format(new Date());  //生产日期
		String tableName = this.createMonthViewNams(proDate);
		Param map = ParamUtil.setParam("tableName", tableName).setParam("proDate", proDate);
		List<MachStatus> statusList = machStatusService.getMachRealTimeStatus(map);
		for(MachInfo mi:machInfoAll) {
			for(MachStatus mstatus : statusList) {
				if(mi.getMachNum().equals(mstatus.getMachNum())) {
					mi.setMachStatus(mstatus.getStatus());
					break;
				}
			}
		}
		return machInfoAll;
	}
	
	private String createMachInfoDiv(String ctx,List<MachInfo> machInfoAll) {
		StringBuilder sb = new StringBuilder();
		int k=0;
		for(int i=0;i<machInfoAll.size();i++) {
			if(i%10 == 0) {
				sb.append("<div class=\"lay2\">");
				for(int j=i;j<i+10;j++) {
					if(j<machInfoAll.size()) {
						if(machInfoAll.get(j).getMachStatus() != null) {
							if(Constant.CNC_MACH_STATUS_RUNNING.contains(machInfoAll.get(j).getMachStatus())) {
								sb.append("<div class=\"horizontal_green\" onclick=\"exportExcel(")
								  .append("'"+machInfoAll.get(j).getMachName()+"')").append("\" >")
								  .append("<img src=\"").append(ctx).append("\\images\\green.jpg\" alt=\"图片\" style=\"vertical-align:middle;\" height=\"50\" width=\"50\"/>")
								  .append(machInfoAll.get(j).getMachName()).append("</div>");
			    			}else if(Constant.CNC_MACH_STATUS_STANDBY.contains(machInfoAll.get(j).getMachStatus())) {
								sb.append("<div class=\"horizontal_red\" onclick=\"exportExcel(")
								  .append("'"+machInfoAll.get(j).getMachName()+"')").append("\" >")
								  .append("<img src=\"").append(ctx).append("\\images\\red.jpg\" alt=\"图片\" style=\"vertical-align:middle;\" height=\"50\" width=\"50\"/>")
							      .append(machInfoAll.get(j).getMachName()).append("</div>");
			    			}else if(Constant.CNC_MACH_STATUS_ALARM.contains(machInfoAll.get(j).getMachStatus())) {
								sb.append("<div class=\"horizontal_yello\" onclick=\"exportExcel(")
								  .append("'"+machInfoAll.get(j).getMachName()+"')").append("\" >")
								  .append("<img src=\"").append(ctx).append("\\images\\yello.jpg\" alt=\"图片\" style=\"vertical-align:middle;\" height=\"50\" width=\"50\"/>")
							      .append(machInfoAll.get(j).getMachName()).append("</div>");
			    			}else if(Constant.CNC_MACH_STATUS_OFFLINE.contains(machInfoAll.get(j).getMachStatus())) {
								sb.append("<div class=\"horizontal_gray\" onclick=\"exportExcel(")
								  .append("'"+machInfoAll.get(j).getMachName()+"')").append("\" >")
								  .append("<img src=\"").append(ctx).append("\\hui.jpg\" alt=\"图片\" style=\"vertical-align:middle;\" height=\"50\" width=\"50\"/>")
							      .append(machInfoAll.get(j).getMachName()).append("</div>");
			    			}
						}else {
		    				sb.append("<div class=\"horizontal_green\" onclick=\"exportExcel(")
							  .append("'"+machInfoAll.get(j).getMachName()+"')").append("\" >")
							  .append("<img src=\"").append(ctx).append("\\images\\green.jpg\" alt=\"图片\" style=\"vertical-align:middle;\" height=\"50\" width=\"50\"/>")
							  .append(machInfoAll.get(j).getMachName()).append("</div>");
		    			}
					}else {
						k=i;
					}
				}
				sb.append("</div>");
			}
		}		
		return sb.toString();
	}
}